/*
 * @Author: Await
 * @Date: 2025-02-23 11:38:32
 * @LastEditors: Await
 * @LastEditTime: 2025-02-23 20:58:37
 * @Description: 请填写简介
 */
import * as vscode from 'vscode';
import { IDebuggerConfig } from './debugConfig';

export class Logger {
    private static instance: Logger | null = null;
    private outputChannel: vscode.OutputChannel;
    private config?: IDebuggerConfig;

    private constructor(config?: IDebuggerConfig) {
        this.outputChannel = vscode.window.createOutputChannel('Cursor C# Debug');
        this.config = config;
    }

    public static getInstance(): Logger {
        if (!Logger.instance) {
            Logger.instance = new Logger();
        }
        return Logger.instance;
    }

    public static initialize(config?: IDebuggerConfig): Logger {
        if (!Logger.instance) {
            Logger.instance = new Logger(config);
        }
        return Logger.instance;
    }

    public debug(...args: any[]): void {
        if (this.config?.logLevel === 'debug') {
            this.log('DEBUG', this.formatMessage(args));
        }
    }

    public info(...args: any[]): void {
        if (this.config?.logLevel !== 'error') {
            this.log('INFO', this.formatMessage(args));
        }
    }

    public warn(...args: any[]): void {
        if (this.config?.logLevel !== 'error') {
            this.log('WARN', this.formatMessage(args));
        }
    }

    public error(...args: any[]): void {
        this.log('ERROR', this.formatMessage(args));
    }

    private formatMessage(args: any[]): string {
        return args.map(arg => {
            if (arg instanceof Error) {
                return arg.message;
            } else if (typeof arg === 'object') {
                try {
                    return JSON.stringify(arg);
                } catch (e) {
                    return '[无法序列化的对象]';
                }
            }
            return String(arg);
        }).join(' ');
    }

    private log(level: string, message: string): void {
        const timestamp = new Date().toISOString();
        this.outputChannel.appendLine(`[${timestamp}] [${level}] ${message}`);
    }

    public show(): void {
        this.outputChannel.show();
    }

    public dispose(): void {
        this.outputChannel.dispose();
    }

    public static reset(): void {
        if (Logger.instance) {
            Logger.instance.dispose();
            Logger.instance = null;
        }
    }
} 